const pageSize = 5; //规定每页请求5条数据
let currentPage = 1; //当前页数
let currentId = null; //要操作得id
let isDelete = null; //操作得行为
getUsers(currentPage);

/**
 *
 * @param {int} page  页码
 * @returns 用户数据列表
 */
function getUsers(page) {
  $.ajax({
    url: "/user/queryUser",
    data: {
      page,
      pageSize
    },
    dataType: "json",
    success: function (res) {
      // console.log(res);
      currentPage = res.page;
      let totalPages = Math.ceil(res.total / res.size);
      renderTable(res.rows);
      setPage(currentPage, totalPages);
    }
  });
}
//渲染table
function renderTable(rows) {
  $(".common-table tbody").html(template("tmp", { rows: rows }));
}
function setPage(totalPages) {
  $("#paginator").bootstrapPaginator({
    // 指定bootstrap版本
    bootstrapMajorVersion: 3,
    // 当前页
    currentPage: currentPage,
    // 总页数
    totalPages: totalPages,

    // 当页面被点击时触发
    onPageClicked: function (a, b, c, page) {
      currentPage = page;
      getUsers(currentPage);
    }
  });
}
//启用按钮点击事件
$(".common-table tbody").on("click", ".btn", function () {
  currentId = $(this).parent().attr("data-id");
  isDelete = $(this).parent().attr("data-delete");
});

//禁用模态框确定按钮的点击事件
$(".model-status").on("click", changeStatus);

//用户禁用/启用
function changeStatus() {
  updateUser(currentId, isDelete);
}
function updateUser(id, isDelete) {
  isDelete = isDelete == 1 ? 0 : 1;
  $.ajax({
    url: "/user/updateUser",
    type: "post",
    dataType: "json",
    data: {
      id,
      isDelete
    },
    success: function (res) {
      $(".model-status").modal("hide");
      if (res.success) {
        getUsers(currentPage);
      } else {
        alert("操作失败");
      }
    }
  });
}
